package com.feri.cs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feri.cs.dao.CarDao;
import com.feri.cs.dao.CarUseDao;
import com.feri.cs.dto.CarUseAdviceDto;
import com.feri.cs.dto.CarUseDto;
import com.feri.cs.dto.TaskDto;
import com.feri.cs.entity.CarUse;
import com.feri.cs.entity.SysUser;
import com.feri.cs.service.CarUseService;
import com.feri.cs.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 3.车辆使用申请表(TCarUse)表服务实现类
 *
 * @author makejava
 * @since 2023-05-09 16:35:01
 */
@Service
@Slf4j
public class CarUseServiceImpl implements CarUseService {
    @Resource
    private CarUseDao dao;
    //查询 运行中 启动实例
    @Resource
    private RuntimeService runtimeService;
    //查询 任务和完成任务
    @Resource
    private TaskService taskService;
    //查询历史记录
    @Resource
    private HistoryService historyService;

    @Override
    public R createUse(CarUseDto dto) {
        Map<String,Object> map=new HashMap<>();
        map.put("sid",dto.getSid());//员工id 申请人
        map.put("day",dto.getDays());
        //2.获取实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("StudyCarUse", map);
        log.info("使用申请流程开始："+processInstance.getId());
        //3.员工任务
        Task task=taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        //4.员工
        taskService.complete(task.getId());
        //5.记录数据库
        dao.insert(new CarUse(dto.getSid(),dto.getCid(),dto.getDays(),processInstance.getId(),dto.getReason()));
        return R.ok(processInstance.getId());
    }

    @Override
    public R queryTask(String role) {
        //1.校验
        if(StringUtils.hasLength(role)){
            if(!role.equals("staff") && !role.equals("admin")){
                List<Task> tasks=taskService.createTaskQuery().taskCandidateGroup(role).list();
                List<TaskDto> list=new ArrayList<>();
                tasks.forEach(t->{
                    CarUse cu=dao.selectOne(new LambdaQueryWrapper<CarUse>().eq(CarUse::getPid,t.getProcessInstanceId()));
                    list.add(new TaskDto(t.getId(),t.getName(),cu.getId()));
                });
                return R.ok(list);
            }
        }
        return R.fail();
    }

    @Override
    public R adviceTask(CarUseAdviceDto dto) {
        //1.更新数据库状态
        if(dao.updateF(getFlag(dto.getRole(),dto.getResult()),dto.getCuid())>0) {
            //2.完成工作流的任务
            Map<String,Object> map=new HashMap<>();
            map.put("result",dto.getResult());
            taskService.complete(dto.getId(),map);
        }
        return R.ok();
    }
    private int getFlag(String role,String result){
        switch (role){
            case "leader":
            {
                if(result.equals("yes")){
                    return 2;
                }else {
                    return 3;
                }
            }
            case "manager":
            {
                if(result.equals("yes")){
                    return 4;
                }else {
                    return 5;
                }
            }
            case "boss":
            {
                if(result.equals("yes")){
                    return 6;
                }else {
                    return 7;
                }
            }
        }
        return 0;
    }
    @Override
    public R queryHistory(String pid) {
        List<HistoricActivityInstance> activities=null;
        if(StringUtils.hasLength(pid)){
            activities = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(pid)
                    .finished()
                    .orderByHistoricActivityInstanceStartTime().asc()
                    .list();
        }else {
            activities = historyService.createHistoricActivityInstanceQuery()
                    .finished()
                    .orderByHistoricActivityInstanceStartTime().asc()
                    .list();
        }
        return R.ok(activities);
    }

    @Override
    public R queryByUid(int id) {
        return R.ok(dao.selectList(new LambdaQueryWrapper<CarUse>().eq(CarUse::getUid,id).orderByDesc(CarUse::getCtime)));
    }
}

